package testsgraphtraversal;

import static org.junit.Assert.*;

import java.util.Iterator;
import java.util.LinkedList;

import graph.AbstractBookReviewGraphConstructor;
import graph.BookReviewGraphConstructorFromTextFile;
import graph.BookReviewGraphInterface;
import graph.BookReviewNode;

import org.junit.Before;
import org.junit.Test;

import visitorpattern.Visitor;
import visitorpattern.VisitorJustPrintsBookReviewNodeInformation;

public class TestGraphTraversal 
{
	/**
	 * graphConstructor is the factory responsible for creating the graph for us
	 */
	private AbstractBookReviewGraphConstructor graphConstructor;
	private BookReviewGraphInterface bookReviewGraph;
	private Visitor visitsNodesOfGraph;
	
	@Before
	public void createGraphForTests()
	{
		graphConstructor = new BookReviewGraphConstructorFromTextFile();
		bookReviewGraph = graphConstructor.createGraph();
		visitsNodesOfGraph = new VisitorJustPrintsBookReviewNodeInformation();
	}
	
	
	

	@Test
	public void testDepthFirst() 
	{
		LinkedList<BookReviewNode> nodesVisited = 
				bookReviewGraph.depthFirstTraversal(visitsNodesOfGraph);
		checkIfTraversalVisitedAllNodes(nodesVisited);
	}
	
	@Test
	public void testBreadthFirst() 
	{
		LinkedList<BookReviewNode> nodesVisited = 
				bookReviewGraph.breadthFirstTraversal(visitsNodesOfGraph);
		checkIfTraversalVisitedAllNodes(nodesVisited);
	}




	private void checkIfTraversalVisitedAllNodes(LinkedList<BookReviewNode> nodesVisited) 
	{
		if(nodesVisited.size() != bookReviewGraph.getNumberOfNodes())
		{
			System.out.println(nodesVisited.size() + "=nodesVisited\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\");
			System.out.println(bookReviewGraph.getNumberOfNodes() + "=nodesInGraph^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^");
			fail("number of nodes visited is not equal to number of nodes in the graph");
		}
		
		
		int numberOfNodesInTheGraph = bookReviewGraph.getNumberOfNodes();
		boolean [] nodesOfGraphWereVisited = new boolean[numberOfNodesInTheGraph];
		for(int i = 0; i < numberOfNodesInTheGraph; i++)
		{
			nodesOfGraphWereVisited[i] = false;
		}
		
		Iterator<BookReviewNode> graphIterator = bookReviewGraph.getBookReviewNodes();
		int indexGraphIterated = 0;
		while(graphIterator.hasNext())
		{
			BookReviewNode nodeFromGraph = graphIterator.next();
			for(int j = 0; j < nodesVisited.size(); j++)
			{
				BookReviewNode nodeVisited = nodesVisited.get(j);
				if(nodeVisited == nodeFromGraph)
				{
					nodesOfGraphWereVisited[j] = true;
				}
			}
			
			indexGraphIterated = indexGraphIterated + 1;
		}
		
		/*now, let's check if there's a node that we haven't visited in the traversal yet
		 * it is in the graph.
		 */
		for(int k = 0; k < nodesOfGraphWereVisited.length; k++)
		{
			if(nodesOfGraphWereVisited[k] == false)
			{
				fail("there was a node of the graph that wasn't visited in the traversal");
			}
		}
	}
	
	
	
	

}
